package org.jaronsource.framework.plugins.security.web.taglib;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.jaronsource.framework.plugins.security.SecurityTokenHolder;
import org.jaronsource.framework.plugins.security.domain.IPerm;
import org.jaronsource.framework.plugins.security.domain.SecurityToken;
import org.jaronsource.framework.util.StringUtils;

public class PermFilterTag extends TagSupport implements Comparator<IPerm> {

	private static final long serialVersionUID = 2703218148455048750L;

	private String groupCode;

	private String parentCode;

	private String var;

	public String getGroupCode() {
		return groupCode;
	}

	public void setGroupCode( String groupCode ) {
		this.groupCode = groupCode;
	}

	public String getParentCode() {
		return parentCode;
	}

	public void setParentCode( String parentCode ) {
		this.parentCode = parentCode;
	}

	public String getVar() {
		return var;
	}

	public void setVar( String var ) {
		this.var = var;
	}

	@Override
	public int doStartTag() throws JspException {
		LinkedList<IPerm> result = new LinkedList<IPerm>();

		this.pageContext.setAttribute( this.var, result );

		SecurityToken token = SecurityTokenHolder.getSecurityToken();
		if ( token == null ) { return SKIP_BODY; }

		Collection<IPerm> perms = token.getPerms();
		List<IPerm> tmpResult = new ArrayList<IPerm>( perms );

		if ( StringUtils.isBlank( groupCode ) ) {
			List<IPerm> tmpResult2 = new ArrayList<IPerm>();
			for ( IPerm perm : tmpResult ) {
				if ( groupCode.equals( perm.getGroupCode() ) ) {
					tmpResult2.add( perm );
				}
				
				if ( groupCode.equals( "__BLANK__" ) && StringUtils.isBlank( perm.getGroupCode()) ) {
					tmpResult2.add( perm );
				}
			}
			tmpResult = tmpResult2;
		}

		if ( !StringUtils.isBlank( parentCode ) ) {
			List<IPerm> tmpResult2 = new ArrayList<IPerm>();
			for ( IPerm perm : tmpResult ) {
				if ( parentCode.equals( perm.getParentCode() ) ) {
					tmpResult2.add( perm );
				}
				
				if ( parentCode.equals( "__BLANK__" ) && StringUtils.isBlank( perm.getParentCode()) ) {
					tmpResult2.add( perm );
				}
			}
			tmpResult = tmpResult2;
		}

		Collections.sort( tmpResult, this );
		
		pageContext.setAttribute( var, tmpResult );

		return SKIP_BODY;
	}

	@Override
	public int compare( IPerm o1, IPerm o2 ) {
		if ( o1.getOrder() == null && o2.getOrder() == null ) return 0;
		if ( o1.getOrder() != null && o2.getOrder() == null ) return 1;
		if ( o1.getOrder() == null && o2.getOrder() != null ) return -1;
		else return o1.getOrder().compareTo( o2.getOrder() );
	}
}
